<template>
  <div>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="用户名" v-model="searchWord"></el-input>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" class="el-icon-search" @click="searchUser(searchWord)">查询</el-button>
          <el-button @click="searchUser('')">清空</el-button>
        </el-col>
      </el-row>
      <div style="margin: 20px 0">
        <el-button type="primary" @click="setUserOrRole('user')">添加</el-button>
        <el-button type="danger">批量删除</el-button>
      </div>
      <!-- @selection-change="handleSelectionChange" -->
      <el-table ref="multipleTable" tooltip-effect="dark" :data="userList" style="width: 100%; margin-bottom: 20px;"
        border @selection-change="selectUser" v-loading="loading">
        <el-table-column type="selection" width="80">
        </el-table-column>
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column label="用户名" width="160" prop="username">
        </el-table-column>
        <el-table-column prop="nickName" label="用户昵称">
        </el-table-column>
        <el-table-column prop="roleName" label="角色列表">
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间">
        </el-table-column>
        <el-table-column prop="gmtModified" label="更新时间">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="分配角色" placement="top">
              <el-button type="primary" class="el-icon-user" size="mini"
                @click="setUserOrRole('role', scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="修改用户信息" placement="top">
              <el-button type="primary" class="el-icon-edit" size="mini"
                @click="setUserOrRole('user', scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="删除用户" placement="top">
              <el-button type="danger" class="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.page"
        :page-sizes="[3, 5, 8]" :page-size="pageInfo.limit" layout="prev, pager, next, jumper, ->, total, sizes"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog title="修改用户" :visible.sync="dialogTableVisible">
      <el-form label-width="100px" v-if="!isSetRole">
        <el-form-item label="用户名">
          <el-input v-model="addUserData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="addUserData.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="addUserData.password"></el-input>
        </el-form-item>
      </el-form>
      <el-form label-width="100px" v-else v-loading="roleLoading">
        <el-form-item label="用户名">
          <el-input v-model="userData.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="ckeckedRoles" @change="roleBeCheck">
            <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="setUserData">保存</el-button>
        <el-button>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { mapState } from 'vuex';
import reqUser from '@/api/userSet'

export default {
  name: 'UserSet',
  data: () => ({
    userList: [],
    total: 0,
    pageInfo: {
      page: 1,
      limit: 8
    },
    loading: false,
    searchWord: '',
    // 保存被选中的角色的id
    selectUserIdList: [],

    // 决定对话框是否弹出及展示对话框中哪一个部分的数据
    dialogTableVisible: false,
    isSetRole: false,

    // 收集新增用户的数据
    addUserData: {
      username: '',
      nickName: '',
      password: ''
    },

    // 收集角色管理复选框、输入框中的数据
    userData: {
      id: "",
      nickName: "",
      password: "",
      roleName: "",
      username: '',
    },
    roleLoading: false,
    checkAll: false,
    ckeckedRoles: [],
    roleList: [],
    isIndeterminate: true
  }),
  // computed: {
  //   ...mapState('userSet', ['userList', 'total'])
  // },
  methods: {

    // 获取用户列表
    async getUserList(username) {
      this.loading = true
      let res = await reqUser.reqUserList(this.pageInfo, username)
      this.userList = res.items
      this.total = res.total
      this.loading = false
    },

    // 分页器页码或每页条数变化时
    handleSizeChange(val) {
      this.pageInfo.limit = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.getUserList()
    },

    // 用户表格某行内容被选中时
    selectUser(selection) {
      this.selectUserIdList = selection.map(item => item.id)
    },

    // 点击查询或清空按钮时
    searchUser(username) {
      this.searchWord = username
      // 点击查询时传入input框收集的数据，点击清空时传入空字符串以清空输入框的内容
      this.pageInfo.page = 1
      // 回到第一页进行搜索
      this.getUserList(username)
    },

    // 删除单个用户
    async delUser(id) {
      await reqUser.reqDelUser(id)
      if (this.userList.length === 1 && this.pageInfo.page !== 1) {
        this.pageInfo.page -= 1
      }
      this.getUserList()
    },

    // 获取角色列表
    async getRoleList(id) {
      this.roleLoading = true
      let res = await reqUser.reqRoleListById(id)
      this.ckeckedRoles = res.assignRoles.map(item => item.id)
      this.roleList = res.allRolesList
      this.roleLoading = false
    },
    // 添加、设置用户或管理角色
    setUserOrRole(flag, userData) {
      this.dialogTableVisible = true
      this.addUserData.username = '' 
      this.addUserData.nickName = '' 
      this.addUserData.password = '' 
      if (flag === 'user') {
        this.isSetRole = false
      } else if (flag === 'role') {
        const { id, nickName, password, roleName, username } = userData
        this.isSetRole = true
        this.userData = { id, nickName, password, roleName, username }
        this.getRoleList(userData.id)
      }
    },
    // 角色管理的选中和全选
    handleCheckAllChange(val) {
      this.ckeckedRoles = val ? this.roleList.map(item => item.roleName) : [];
      this.isIndeterminate = false;
    },
    roleBeCheck(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
    },

    // 点击保存按钮的逻辑
    async setUserData() {
      if (this.isSetRole) {
        let roleName = ''
        this.ckeckedRoles.forEach(item => {
          roleName += item + ','
        })
        roleName = roleName.slice(0, roleName.length - 1)
        this.userData.roleName = roleName
        this.userData.roleName = this.ckeckedRoles
        console.log(roleName);
        // console.log(this.userData.id);
        await reqUser.reqSetRole(this.userData.id, roleName)
      } else {
        await reqUser.reqAddUser(this.addUserData)
      }
      this.dialogTableVisible = false
      this.getUserList()
    }

  },
  mounted() {
    this.getUserList()
  }
}
</script>

<style scoped></style>

